package org.apache.guacamole.auth;

import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleServerException;
import org.apache.guacamole.environment.Environment;
import org.apache.guacamole.environment.LocalEnvironment;
import org.apache.guacamole.net.auth.Credentials;
import org.apache.guacamole.net.auth.simple.SimpleAuthenticationProvider;
import org.apache.guacamole.protocol.GuacamoleConfiguration;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * Authentication provider implementation intended to demonstrate basic use
 * of Guacamole's extension API. The credentials and connection information for
 * a single user are stored directly in guacamole.properties.
 */
public class TutorialAuthenticationProvider extends SimpleAuthenticationProvider {

  @Override
  public String getIdentifier() {
    return "tutorial";
  }

  @Override
  public Map<String, GuacamoleConfiguration> getAuthorizedConfigurations(Credentials credentials) throws GuacamoleException {

    var rq = credentials.getRequest();

    System.out.println(rq.getClass().getCanonicalName());

    var paraNames = rq.getParameterNames();
    while (paraNames.hasMoreElements()) {
      String thisName = paraNames.nextElement().toString();
      String thisValue = rq.getParameter(thisName);
      System.out.println(thisName + " = " + thisValue);
    }


    var key = rq.getParameter("key");
    System.out.println("key_: " + key);
    var expires = rq.getParameter("expires");
    System.out.println("expires_: " + expires);
    try {
      if (key != null && expires != null && Integer.valueOf(expires) != null) {
        var jedis = new Jedis("127.0.0.1", 6379);
        jedis.connect();
        jedis.set("guest_password", key);
        jedis.expire("guest_password", Long.parseLong(expires));
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    // Get the Guacamole server environment
    Environment environment = new LocalEnvironment();

    if ("guest".equalsIgnoreCase(credentials.getUsername())) {
      //访客，走访客的验证方式
      var jedis = new Jedis("127.0.0.1", 6379);
      jedis.connect();
      if (!jedis.exists("guest_password")) {
        return null;
      }
      var password = jedis.get("guest_password");
      System.out.println("guest_password: " + password);
      if (!password.equalsIgnoreCase(credentials.getPassword())) {
        return null;
      }
    } else {
      // Get username from guacamole.properties
      String username = environment.getRequiredProperty(
              TutorialGuacamoleProperties.TUTORIAL_USER
      );

      // If wrong username, fail
      if (!username.equals(credentials.getUsername())) {
        return null;
      }

      // Get password from guacamole.properties
      String password = environment.getRequiredProperty(
              TutorialGuacamoleProperties.TUTORIAL_PASSWORD
      );

      // If wrong password, fail
      if (!password.equals(credentials.getPassword())) {
        return null;
      }
    }

    // Successful login. Return configurations.
    Map<String, GuacamoleConfiguration> configs =
            new HashMap<String, GuacamoleConfiguration>();

    // Create new configuration
    GuacamoleConfiguration config = new GuacamoleConfiguration();

    // Set protocol specified in properties
    config.setProtocol(environment.getRequiredProperty(
            TutorialGuacamoleProperties.TUTORIAL_PROTOCOL
    ));

    // Set all parameters, splitting at commas
    for (String parameterValue : environment.getRequiredProperty(
            TutorialGuacamoleProperties.TUTORIAL_PARAMETERS
    ).split(",\\s*")) {

      // Find the equals sign
      int equals = parameterValue.indexOf('=');
      if (equals == -1) {
        throw new GuacamoleServerException("Required equals sign missing");
      }

      // Get name and value from parameter string
      String name = parameterValue.substring(0, equals);
      String value = parameterValue.substring(equals + 1);

      // Set parameter as specified
      config.setParameter(name, value);

    }

    configs.put("archem power connection", config);
    return configs;

  }

}